<?php
class Follow_model extends CI_Model {
	
	public function follow($uid,$bid){
		if ($this->is_follow($uid, $bid)){
			echo -1;
		} else {
			$this->db->insert('follow',array(
					'uid'=>$uid,
					'bid'=>$bid,
			));
			return $this->db->insert_id();
		}
	}
	
	public function unfollow($uid,$bid){
		if ($this->is_follow($uid, $bid)) {
			$this->db->delete('follow', array('uid' => $uid,'bid'=>$bid));
			return true;
		} else {
			return false;
		}
		
	}
	
	public function is_follow($uid,$bid){
		$this->db->where('uid',$uid);
		$this->db->where('bid',$bid);
		return $this->db->count_all_results("follow")>0;
	}
	
	public function get_follow_blogs($uid,$detail = false){
		$sql = "select bid,bname from blog where bid in(
				select bid from follow where uid = ?
			)";
		$query = $this->db->query($sql,array($uid));
		if ($detail) {
			return $this->attacth_detail($query->result_array());
		} else {
			return $query->result_array();
		}
	}
	
	public function get_follow_num($bid){
		$this->db->where('bid',$bid);
		return $this->db->count_all_results("follow");
	}
	
	public function get_follow_posts($uid){
		$sql = "select * from post where bid in (
				select bid from follow where uid = ?
			)";
		$query = $this->db->query($sql,array($uid));
		return $query->result_array();
	}
	
	private function attacth_detail($blogs){
		foreach ($blogs as &$blog){
			$bid = $blog['bid'];
			$editors = $this->get_editors($bid);
			$blog['editors'] = $editors;
			$blog['creator'] = $this->get_creator($bid);
		}
		return $blogs;
	}
	

	public function get_followers($bid){
		$sql = "select * from user where uid in (select uid from follow where bid = ?)";
		$query = $this->db->query($sql,array($bid));
		return $query->result_array(); 
	}
	
}

?>